<template>
    <n-drawer :show="active" :width="width" @update:show="(flag:boolean) => (active = flag)">
        <n-drawer-content :native-scrollbar="false" title="车系详情" closable>
            <n-spin :show="loading">
                <n-space vertical :size="24">
                    <n-card v-if="serie.id" size="small">
                        <n-form label-placement="left" inline :show-feedback="false">
                            <n-form-item label="车系编号">
                                <b>{{ serie.id }}</b>
                            </n-form-item>
                            <n-form-item label="名称">
                                <b>{{ serie.name }}</b>
                            </n-form-item>
                            <n-form-item label="品牌">
                                <n-space>
                                    <b>{{ serie.brand.name }}</b>
                                    /
                                    <b>{{ serie.corp?.name }}</b>
                                </n-space>
                            </n-form-item>
                            <n-form-item label="分组">
                                <n-button
                                    type="primary"
                                    size="small"
                                    v-if="!addGroup"
                                    @click="
                                        () => {
                                            addGroup = true
                                        }
                                    "
                                >
                                    添加分组
                                </n-button>
                                <n-space v-else :align="`center`">
                                    <n-date-picker size="small" :style="{ width: '200px' }" :is-date-disabled="yearFilter" close-on-select update-value-on-close v-model:value="years" type="yearrange" />
                                    <n-button
                                        size="small"
                                        type="primary"
                                        @click="
                                            () => {
                                                execSaveYearGroup()
                                            }
                                        "
                                    >
                                        保存
                                    </n-button>
                                    <n-button
                                        size="small"
                                        type="error"
                                        @click="
                                            () => {
                                                addGroup = false
                                            }
                                        "
                                    >
                                        取消
                                    </n-button>
                                </n-space>
                            </n-form-item>
                        </n-form>
                    </n-card>

                    <n-card v-if="serie.id" size="small">
                        <n-form label-placement="left" inline :show-feedback="false">
                            <n-form-item label="车系类型">
                                <n-select :default-value="serie.type.id" :style="{ width: '200px' }" size="small" clearable placeholder="车辆类型" :options="typeOpts" @update:value="(val:string) => (execTypeSet(val))" />
                            </n-form-item>
                            <n-form-item label="自定义属性">
                                <n-space :align="`center`">
                                    <n-switch size="medium" v-model:value="serie.prop" @update:value="(val:boolean) => !val && execPropSet(val)" />
                                    <n-select v-if="serie.prop" v-model:value="props" :style="{ width: '200px' }" size="small" placeholder="车辆属性" :options="propOpts" @update:value="onPropChange" />
                                </n-space>
                            </n-form-item>
                            <n-form-item label="属性筛选" v-if="serie.prop && props">
                                <n-radio-group v-model:value="filterProp" name="propgroup" @update:value="filterProps">
                                    <n-space>
                                        <n-radio key="" value="">所有</n-radio>
                                        <n-radio v-for="song in propsOpts" :key="song.title" :value="song.title">
                                            {{ song.title }}
                                        </n-radio>
                                    </n-space>
                                </n-radio-group>
                            </n-form-item>
                        </n-form>
                    </n-card>
                    <n-card v-if="serie.id" size="small">
                        <n-collapse :default-expanded-names="defNames">
                            <n-collapse-item :title="`默认图片 共 ${dimgs.length} 张`" name="default">
                                <n-grid :cols="4" v-if="dimgs.length > 0" :x-gap="12" :y-gap="12">
                                    <n-gi :span="1" v-for="cover in dimgs">
                                        <n-card size="small">
                                            <n-space vertical>
                                                <n-image :width="width / 4 - 50" :height="((width / 4 - 50) / 5) * 3" object-fit="cover" :src="cover.url" />
                                                <n-space justify="space-between" :style="{ width: '100%' }" :align="'center'">
                                                    <n-space size="small">
                                                        <n-text>{{ cover.year }}款</n-text>
                                                        <n-text>{{ cover.color }}</n-text>
                                                        <n-text v-if="serie.prop">{{ cover.type }}</n-text>
                                                    </n-space>
                                                    <n-button type="info" size="tiny" @click="() => doEdit(cover)">编辑</n-button>
                                                </n-space>
                                            </n-space>
                                        </n-card>
                                    </n-gi>
                                </n-grid>
                                <n-empty v-else></n-empty>
                            </n-collapse-item>
                            <n-collapse-item v-for="(covers, year) in yimgs" :title="`${year} 款 共 ${covers.length} 张`" :name="year">
                                <template #header-extra>
                                    <n-popconfirm
                                        :negative-text="null"
                                        @positive-click="
                                            () => {
                                                execDeleteYearGroup(`${year}`)
                                            }
                                        "
                                    >
                                        <template #trigger>
                                            <n-button type="error" size="tiny" @click.stop="() => {}">删除分组</n-button>
                                        </template>
                                        是否删除年份分组？
                                    </n-popconfirm>
                                </template>
                                <n-grid :cols="4" v-if="covers.length > 0" :x-gap="12" :y-gap="12">
                                    <n-gi :span="1" v-for="cover in covers">
                                        <n-card size="small">
                                            <n-space vertical>
                                                <n-image :width="width / 4 - 50" :height="((width / 4 - 50) / 5) * 3" object-fit="cover" :src="cover.url" />
                                                <n-space justify="space-between" :style="{ width: '100%' }" :align="'center'">
                                                    <n-space size="small">
                                                        <n-text>{{ cover.year }}款</n-text>
                                                        <n-text>{{ cover.color }}</n-text>
                                                        <n-text v-if="serie.prop">{{ cover.type }}</n-text>
                                                    </n-space>
                                                    <n-space>
                                                        <n-button type="info" size="tiny" @click="() => doEdit(cover)">编辑</n-button>
                                                        <n-button type="warning" :disabled="cover.default" size="tiny" @click="() => doDelete(cover)">删除</n-button>
                                                    </n-space>
                                                </n-space>
                                            </n-space>
                                        </n-card>
                                    </n-gi>
                                </n-grid>
                                <n-empty v-else></n-empty>
                            </n-collapse-item>
                            <n-collapse-item :title="`未分组图片 共 ${nimgs.length} 张`" name="none" v-if="nimgs.length > 0">
                                <n-grid :cols="4" :x-gap="12" :y-gap="12">
                                    <n-gi :span="1" v-for="cover in nimgs">
                                        <n-card size="small">
                                            <n-space vertical>
                                                <n-image :width="width / 4 - 50" :height="((width / 4 - 50) / 5) * 3" object-fit="cover" :src="cover.url" />
                                                <n-space justify="space-between" :style="{ width: '100%' }" :align="'center'">
                                                    <n-space size="small">
                                                        <n-text>{{ cover.year }}款</n-text>
                                                        <n-text>{{ cover.color }}</n-text>
                                                        <n-text v-if="serie.prop">{{ cover.type }}</n-text>
                                                    </n-space>
                                                    <n-space>
                                                        <n-button type="info" size="tiny" @click="() => doEdit(cover)">编辑</n-button>
                                                        <n-button type="warning" :disabled="cover.default" size="tiny" @click="() => doDelete(cover)">删除</n-button>
                                                    </n-space>
                                                </n-space>
                                            </n-space>
                                        </n-card>
                                    </n-gi>
                                </n-grid>
                            </n-collapse-item>
                        </n-collapse>
                    </n-card>
                </n-space>
            </n-spin>

            <template #footer>
                <n-space justify="space-between" :style="{ width: '100%' }">
                    <n-space>
                        <n-button v-if="!form" size="small" type="info" @click="doAdd">添加图片</n-button>
                        <n-form v-else inline size="small" :model="model" :rule="rules" :show-label="false" :show-feedback="false" ref="formRef">
                            <n-form-item>
                                <n-checkbox v-model:checked="model.default">默认图片</n-checkbox>
                            </n-form-item>
                            <n-form-item :style="{ width: '130px' }">
                                <n-input-number v-model:value="model.year" :min="1970">
                                    <template #suffix>款</template>
                                </n-input-number>
                            </n-form-item>
                            <n-form-item :style="{ width: '130px' }">
                                <n-select v-model:value="model.color" filterable tag placeholder="车身颜色" :options="colorOpts" />
                            </n-form-item>
                            <n-form-item :style="{ width: '150px' }" v-if="serie.prop">
                                <n-select v-model:value="model.type" placeholder="车辆属性" clearable :options="propsOpts" label-field="title" value-field="id" />
                            </n-form-item>
                            <n-form-item>
                                <n-popover trigger="hover" v-if="model.url">
                                    <template #trigger>
                                        <n-space>
                                            <ButtonUpload v-model:value="model.url" type="Image" accept="image/png,image/jpeg,image/webp" title="上传图片" />
                                        </n-space>
                                    </template>
                                    <n-image width="400" height="300" object-fit="cover" :src="model.url" />
                                </n-popover>
                                <ButtonUpload v-else v-model:value="model.url" type="Image" accept="image/png,image/jpeg,image/webp" title="上传图片" />
                            </n-form-item>
                            <n-form-item>
                                <n-space>
                                    <n-button type="primary" @click="execSave">保存</n-button>
                                    <n-button @click="() => (form = false)">取消</n-button>
                                </n-space>
                            </n-form-item>
                        </n-form>
                    </n-space>
                    <n-button @click="() => (active = false)">
                        <template #icon>
                            <n-icon :component="CloseRound" />
                        </template>
                        关闭
                    </n-button>
                </n-space>
            </template>
        </n-drawer-content>
    </n-drawer>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref } from 'vue'
import { CloseRound } from '@vicons/material'
import { useStore } from '@/store'
import { Http } from '@/libs'
import ButtonUpload from '@/comp/func/ButtonUpload.vue'

const store = useStore()
const width = computed(() => Math.max(store.state.browser.innerWidth * 0.4, 1300))
const loading = computed(() => store.state.loading.flag)

const { $notification: notification } = window
const { $dialog: dialog } = window

const prop = defineProps({
    show: {
        type: Boolean,
        required: true,
    },
    item: {
        type: Object,
        required: true,
    },
})

const defNames = ref<any[]>(['default'])

const emit = defineEmits(['update:show', 'refresh'])

const active = computed({
    get: () => prop.show,
    set: val => emit('update:show', val),
})

const form = ref<boolean>(false)

const formRef = ref<any>(null)

const model = ref<any>({})

const rules = {
    year: {
        required: true,
        type: 'number',
        trigger: ['blur', 'input'],
        message: '请填写年款',
    },
    color: {
        required: true,
        trigger: ['blur', 'input'],
        message: '请填写颜色',
    },
    type: {
        required: true,
        trigger: ['blur', 'input'],
        message: '请填写类型',
    },
}

const doEdit = (cover: any) => {
    model.value = {
        id: cover.id,
        year: cover.year,
        color: cover.color,
        door: cover.door,
        type: cover.type,
        url: cover.url,
        default: cover.default,
    }
    form.value = true
}

const doAdd = () => {
    model.value = {
        id: '',
        year: new Date().getFullYear(),
        color: undefined,
        door: 4,
        type: '',
        url: '',
        default: false,
    }
    form.value = true
}
const filterProp = ref<string>('')
const filterProps = () => {
    let prop = filterProp.value || ''
    let dimg: any = []
    let nimg: any = []
    let yimg: any = {}

    serie.value.yearg.forEach((yg: any) => {
        yimg[`${yg.begin} - ${yg.close}`] = []
    })

    serie.value.covers.forEach((cover: any) => {
        if (prop == '' || cover.type == prop) {
            if (cover.default) {
                dimg[dimg.length] = cover
            }
            let flag = false
            serie.value.yearg.forEach((yg: any) => {
                if (!flag && yg.begin <= cover.year && yg.close >= cover.year) {
                    yimg[`${yg.begin} - ${yg.close}`][yimg[`${yg.begin} - ${yg.close}`].length] = cover
                    flag = true
                }
            })
            if (!flag) {
                nimg[nimg.length] = cover
            }
        }
    })
    dimgs.value = dimg
    yimgs.value = yimg
    nimgs.value = nimg
}

const yearFilter = (ts: number, type: 'start' | 'end', range: [number, number] | null) => {
    console.log(ts, type, range)
    // if (type === 'start' && range !== null) {
    //   return (
    //     startOfDay(range[1]).valueOf() - startOfDay(ts).valueOf() <= d * 6
    //   )
    // }
    // if (type === 'end' && range !== null) {
    //   return (
    //     startOfDay(ts).valueOf() - startOfDay(range[0]).valueOf() <= d * 6
    //   )
    // }
    return false
}

const execSave = (e: Event) => {
    e.preventDefault()
    formRef.value.validate((errors: any[]) => {
        if (!errors) {
            Http.post('/ops/sys/car/model/image/save', {
                sid: serie.value.id,
                cover: model.value,
            }).then(resp => {
                if (resp.stat.err > 0) {
                    return
                }
                execLoad()
                form.value = false
                emit('refresh', {})
                notification.success({
                    duration: 1500,
                    title: '操作成功',
                    content: model.value.id ? '您已成功修改图片' : '您已成功添加图片',
                })
            })
        } else {
            let msgs = errors.map(err => err[0].message)
            notification.error({
                duration: 1500,
                title: '请填写完整内容',
                description: '当前表单存在以下问题，请处理后提交',
                content: msgs.join('\n'),
            })
        }
    })
}

const doDelete = (row: any) => {
    dialog.error({
        title: `提示?`,
        content: `是否删除 [ ${row.year} / ${row.color} / ${row.type} ] 这张图片?`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
            execDelete(row.id)
        },
    })
}

const execDelete = (id: string) => {
    Http.post('/ops/sys/car/model/image/delete', {
        sid: serie.value.id,
        id: id,
    }).then(resp => {
        if (resp.stat.err > 0) {
            return
        }
        execLoad()
        emit('refresh', {})
        notification.success({
            duration: 1500,
            title: '操作成功',
            content: '您已成功删除图片',
        })
    })
}

const execLoadDict = () => {
    Http.post('/comm/data/dict', { key: 'serie_type' }).then(resp => {
        if (resp.stat.err > 0) {
            return
        }
        typeOpts.value = resp.data.items.map((item: any) => {
            return {
                label: item.name,
                value: item.val,
            }
        })
    })
    Http.post('/comm/data/dict', { key: 'serie_prop' }).then(resp => {
        if (resp.stat.err > 0) {
            return
        }
        propOpts.value = resp.data.items.map((item: any) => {
            return {
                label: JSON.parse(item.name)
                    .map((i: any) => i.title)
                    .join(' / '),
                value: item.val,
            }
        })
        let opt: any = resp.data.items.find((item: any) => item.val == props.value)
        if (opt) {
            propsOpts.value = JSON.parse(opt.name)
        }
    })
}

const typeOpts = ref<any[]>([])

const execTypeSet = (type: string) => {
    Http.post('/ops/sys/car/model/type/set', {
        sid: serie.value.id,
        type: type,
    }).then(resp => {
        if (resp.stat.err > 0) {
            return
        }
        execLoad()
        emit('refresh', {})
        notification.success({
            duration: 1500,
            title: '操作成功',
            content: '您已成功设置车型',
        })
    })
}
const propOpts = ref<any[]>([])
const props = ref<any>(undefined)
const propsOpts = ref<any[]>([])

const onPropChange = () => {
    execPropSet(true)
}

const execPropSet = (prop: boolean) => {
    Http.post('/ops/sys/car/model/prop/set', {
        sid: serie.value.id,
        prop: prop,
        props: prop ? props.value : '',
    }).then(resp => {
        if (resp.stat.err > 0) {
            return
        }
        execLoad()
        notification.success({
            duration: 1500,
            title: '操作成功',
            content: '您已成功设置自定义属性',
        })
    })
}

const addGroup = ref<boolean>(false)
const years = ref<[number, number]>([Date.now(), Date.now()])

const execSaveYearGroup = () => {
    Http.post('/ops/sys/car/model/year/group/add', {
        sid: serie.value.id,
        begin: new Date(years.value[0]).getFullYear(),
        close: new Date(years.value[1]).getFullYear(),
    }).then(resp => {
        if (resp.stat.err > 0) {
            return
        }
        execLoad()
        addGroup.value = false
    })
}

const execDeleteYearGroup = (year: string) => {
    Http.post('/ops/sys/car/model/year/group/delete', {
        sid: serie.value.id,
        begin: parseInt(year.split('-')[0].trim()),
        close: parseInt(year.split('-')[1].trim()),
    }).then(resp => {
        if (resp.stat.err > 0) {
            return
        }
        execLoad()
        addGroup.value = false
    })
}

const serie = ref<any>({})
const colorOpts = ref<any>([])

const dimgs = ref<any>([])
const yimgs = ref<any>({})
const nimgs = ref<any>({})

const execLoad = () => {
    Http.post('/ops/sys/car/model/serie/detail', { id: prop.item.id }).then(resp => {
        if (resp.stat.err > 0) {
            return
        }
        colorOpts.value = resp.data.colors.map((x: any) => {
            return { label: x, value: x }
        })
        let dimg: any = []
        let nimg: any = []
        let yimg: any = {}

        resp.data.yearg.forEach((yg: any) => {
            yimg[`${yg.begin} - ${yg.close}`] = []
        })

        resp.data.covers.forEach((cover: any) => {
            if (filterProp.value == '' || cover.type == filterProp.value) {
                if (cover.default) {
                    dimg[dimg.length] = cover
                }
                let flag = false
                resp.data.yearg.forEach((yg: any) => {
                    if (!flag && yg.begin <= cover.year && yg.close >= cover.year) {
                        yimg[`${yg.begin} - ${yg.close}`][yimg[`${yg.begin} - ${yg.close}`].length] = cover
                        flag = true
                    }
                })
                if (!flag) {
                    nimg[nimg.length] = cover
                }
            }
        })
        dimgs.value = dimg
        yimgs.value = yimg
        nimgs.value = nimg
        props.value = resp.data.props ? resp.data.props : undefined
        serie.value = resp.data
        execLoadDict()
    })
}

onMounted(() => {
    execLoad()
})
</script>
